package com.yilin.tms.user.controller;

import com.yilin.commons.encrypt.EncryptUtils;
import com.yilin.commons.encrypt.KeyPairMap;
import com.yilin.commons.encrypt.Md5Util;
import com.yilin.commons.util.StringUtil;
import com.yilin.tms.core.application.AppUtil;
import com.yilin.tms.core.application.ReturnData;
import com.yilin.tms.core.commons.utils.ParamUtil;
import com.yilin.tms.core.commons.utils.SMSUtil;
import com.yilin.tms.core.commons.utils.UserUtil;
import com.yilin.tms.core.commons.base.BaseController;
import com.yilin.tms.core.commons.annotation.SkipLoginVerify;
import com.yilin.tms.core.components.redis.RedisClient;
import com.yilin.tms.core.components.redis.RedisKeys;
import com.yilin.tms.core.entity.system.system.Jurisdiction;
import com.yilin.tms.core.entity.user.account.Account;
import com.yilin.tms.core.entity.user.OrganType;
import com.yilin.tms.core.entity.user.RoleType;
import com.yilin.tms.core.entity.user.UserType;
import com.yilin.tms.core.entity.user.account.Authority;
import com.yilin.tms.core.entity.user.hatch.HatchPlatProduct;
import com.yilin.tms.core.entity.user.organize.Organize;
import com.yilin.tms.core.entity.user.organize.UserRole;
import com.yilin.tms.core.remote.ISystemRemote;
import com.yilin.tms.user.service.IAccountService;
import com.yilin.tms.user.service.IHatchService;
import com.yilin.tms.user.service.IOrganizeService;
import com.yilin.tms.user.service.IRoleService;
import com.yilin.tms.user.service.impl.AuthorityService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/***
 * API认证鉴权控制器
 * 用户注册中心
 *
 *  提供所有用户的注册渠道
 *
 * */
@RestController
@RequestMapping("/user/register/")
public class RegisterController extends BaseController {

    @Resource
    private IOrganizeService organizeService;
    @Resource
    private IHatchService hatchService;
    @Resource
    private IAccountService accountService;




    /**
     * 极舜货运 初始化渠道 直接通过接口初始化即可
     * 仅能通过超级管理员添加
     */
    @PostMapping("yilinRegister")
    public ReturnData yilinRegister(Organize organize, Account account) {
        Organize adminOrganize = organizeService.getAdminOrganize();
        if (adminOrganize != null) return jsonView(false, "易林商户已存在，不能重复添加！");
        Account loginUser = UserUtil.getLoginUser(request);
        if (loginUser == null || loginUser.getUserType() != UserType.adminUser) {
            return jsonView(false, "仅超级管理员用户可以管理极舜货运商户信息！");
        }
        if (StringUtil.isEmpty(organize.getOrganizeName())) {
            organize.setOrganizeName("贵州极舜货运");
        }
        if (StringUtil.isEmpty(organize.getOrganizeTel())) {
            organize.setOrganizeTel("400-6785656");
        }
        if (StringUtil.isEmpty(organize.getLegalName())) {
            organize.setLegalName("何运蕾");
        }
        if (StringUtil.isEmpty(organize.getLegalPhone())) {
            organize.setLegalPhone("13017438777");
        }
        if (StringUtil.isEmpty(account.getName())) {
            account.setName("程登宇");
        }
        if (StringUtil.isEmpty(account.getPhone())) {
            account.setPhone("15286063702");
        }
        if (StringUtil.isEmpty(account.getUsername())) {
            account.setUsername("ylwl");
        }
        if (StringUtil.isEmpty(account.getPassword())) {
            account.setPassword("12345678");
        }
        //###初始化商户信息
        Organize superPlatOrganize = organizeService.getOrganizeById(loginUser.getOrganizeId());
        organize.setOrganType(OrganType.company);
        organize.setSuperiorPlatOrganizeId(loginUser.getOrganizeId());
        organize.setSuperiorPlatOrganizeName(loginUser.getOrganizeName());
        //###初始化账户信息
        account.setOrganType(OrganType.company);
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.web);
        //完成用户添加注册
        organize.setAddUserId(loginUser.getId());
        account.setAddUserId(loginUser.getId());
        organizeService.organizeRegister(organize, account);
        return jsonView(true, "客户注册成功！");
    }

    /**
     * 区域商户注册渠道，注册后，分配区域壳服务器
     * 注册自动创建组织信息 + 一个组织管理员账户
     */
    @PostMapping("zoneRegister")
    public ReturnData zoneRegister(Organize organize, Account account) {
        Account loginUser = getLoginUser();
        if (StringUtil.isEmpty(organize.getOrganizeName())) {
            return jsonView(false, "请填写区域客户（公司）名称！");
        }
        if (StringUtil.isEmpty(organize.getOrganizeTel())) {
            return jsonView(false, "请填写区域客户（公司）电话！");
        }
        if (StringUtil.isEmpty(organize.getLegalName())) {
            return jsonView(false, "请填写法人姓名！");
        }
        if (StringUtil.isEmpty(organize.getLegalPhone())) {
            return jsonView(false, "请填写法人手机号！");
        }
        if (StringUtil.isEmpty(account.getName())) {
            return jsonView(false, "请填写公司账户管理员姓名！");
        }
        if (StringUtil.isEmpty(account.getPhone())) {
            return jsonView(false, "请填写公司账户管理员手机号（用于密码找回）！");
        }
        if (StringUtil.isEmpty(account.getUsername())) {
            return jsonView(false, "请为区域客户生成一个账号（4-16位）！");
        }
        if (account.getUsername().length() < 4) {
            return jsonView(false, "账号小于4位，请将账号控制在（4-16位）！");
        }
        if (account.getUsername().length() > 16) {
            return jsonView(false, "账号大于16位，请将账号控制在（4-16位）！");
        }
        if (StringUtil.isEmpty(account.getPassword())) {
            return jsonView(false, "请为区域客户生成一个密码（8-18位）！");
        }
        if (account.getPassword().length() < 8) {
            return jsonView(false, "密码小于8位，请将密码控制在（8-18位）！");
        }
        if (account.getPassword().length() > 18) {
            return jsonView(false, "密码大于16位，请将密码控制在（8-18位）！");
        }
        //###初始化商户信息
        organize.setOrganType(OrganType.company);
        organize.setSuperiorPlatOrganizeId(loginUser.getOrganizeId());
        organize.setSuperiorPlatOrganizeName(loginUser.getOrganizeName());
        //###初始化账户信息
        account.setOrganType(OrganType.company);
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.web);
        account.setLoginType(Account.LoginType.pass);
        //完成用户添加注册
        organize.setAddUserId(loginUser.getId());
        account.setAddUserId(loginUser.getId());
        organizeService.organizeRegister(organize, account);
        return jsonView(true, "客户注册成功！");
    }

    /**
     * 网货商户注册渠道，注册后，分配区域壳服务器
     * 注册自动创建组织信息 + 一个组织管理员账户
     */
    @PostMapping("platformRegister")
    public ReturnData platformRegister(Organize organize, Account account) {
        Account loginUser = getLoginUser();
        if (StringUtil.isEmpty(organize.getOrganizeName())) {
            return jsonView(false, "请填写网货客户（公司）名称！");
        }
//        if (StringUtil.isEmpty(organize.getProductName())) {
//            return jsonView(false, "请设置一个网货系统产品名称！");
//        }
//        if (StringUtil.isEmpty(organize.getProductCode())) {
//            return jsonView(false, "请设置一个网货系统产品代码！");
//        }
        if (StringUtil.isEmpty(organize.getOrganizeTel())) {
            return jsonView(false, "请填写网货客户（公司）电话！");
        }
        if (StringUtil.isEmpty(organize.getLegalName())) {
            return jsonView(false, "请填写公司法人姓名！");
        }
        if (StringUtil.isEmpty(organize.getLegalPhone())) {
            return jsonView(false, "请填写公司法人手机号！");
        }
        if (StringUtil.isEmpty(account.getName())) {
            return jsonView(false, "请填写公司账户管理员姓名！");
        }
        if (StringUtil.isEmpty(account.getPhone())) {
            return jsonView(false, "请填写公司账户管理员手机号（用于密码找回）！");
        }
        if (StringUtil.isEmpty(account.getUsername())) {
            return jsonView(false, "请为网货客户生成一个账号（4-16位）！");
        }
        if (account.getUsername().length() < 4) {
            return jsonView(false, "账户小于4位，请将账户控制在（4-16位）！");
        }
        if (account.getUsername().length() > 16) {
            return jsonView(false, "账户大于16位，请将账户控制在（4-16位）！");
        }
        if (StringUtil.isEmpty(account.getPassword())) {
            return jsonView(false, "请为网货客户生成一个密码（8-16位）！");
        }
        if (account.getPassword().length() < 8) {
            return jsonView(false, "密码小于8位，请将密码控制在（8-18位）！");
        }
        if (account.getPassword().length() > 18) {
            return jsonView(false, "密码大于16位，请将密码控制在（8-18位）！");
        }
        //###初始化商户信息
        Organize superPlatOrganize = organizeService.getOrganizeById(loginUser.getOrganizeId());
        organize.setUserType(UserType.platformUser);
        organize.setOrganType(OrganType.company);
        organize.setSuperiorPlatOrganizeId(loginUser.getOrganizeId());
        organize.setSuperiorPlatOrganizeName(superPlatOrganize.getOrganizeName());
        //###初始化账户信息
        account.setName(organize.getOrganizeName()+"管理员");
        account.setUserType(UserType.platformUser);
        account.setOrganType(OrganType.company);
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.web);
        //###完成用户添加注册
        organize.setAddUserId(loginUser.getId());
        account.setAddUserId(loginUser.getId());
        organizeService.organizeRegister(organize, account);
        return jsonView(true, "客户注册成功！");
    }

    /**
     * 货主/司机 手动注册渠道
     * 验证码注册
     */
    @PostMapping("customerRegister")
    @SkipLoginVerify //不需要登录就可以访问
    public ReturnData customerRegister(Organize organize, Account account) {
        Account loginUser = getLoginUser();
        if (loginUser == null || loginUser.getUserType() != UserType.platformUser) {
            return jsonView(false, "仅网货平台用户可以管理货主/司机信息！");
        }
        if (StringUtil.isEmpty(organize.getOrganizeName())) {
            return jsonView(false, "请填写货主（企业）组织名称！");
        }
        if (StringUtil.isEmpty(organize.getOrganizeTel())) {
            return jsonView(false, "请填写货主（企业）组织电话！");
        }
        if (StringUtil.isEmpty(account.getName())) {
            return jsonView(false, "请填写管理员账户姓名！");
        }
        if (StringUtil.isEmpty(account.getPhone())) {
            return jsonView(false, "请填写管理员账户手机号（用于密码找回）！");
        }
        if (StringUtil.isEmpty(account.getUsername())) {
            return jsonView(false, "请为货主生成一个账号（4-16位）！");
        }
        if (account.getUsername().length() < 4) {
            return jsonView(false, "账号设置小于8位，请将账号长度控制在（4-16位）！");
        }
        if (account.getUsername().length() > 16) {
            return jsonView(false, "账号设置大于16位，请将账号长度控制在（4-16位）！");
        }
        if (StringUtil.isEmpty(account.getPassword())) {
            return jsonView(false, "请为货主客户生成一个密码（8-18位）！");
        }
        if (account.getPassword().length() < 8) {
            return jsonView(false, "密码长度小于8位，请将密码控制在（8-18位）！");
        }
        if (organize.getUserType() == null) {
            return jsonView(false, "未知用户类型！");
        }
        if (organize.getUserType() != UserType.shipperUser && organize.getUserType() != UserType.truckerUser) {
            return jsonView(false, "用户类型设置错误！");
        }
        if (organize.getOrganType() == null) {
            return jsonView(false, "未知的组织类型，请选择个体或公司！");
        }
        //检查验证码
        Map<String, Object> verifyCode = SMSUtil.verifyCode(account.getPhone(), account.getVerCode(), SMSUtil.MsgType.organizeRegister);
        if (!(Boolean) verifyCode.get(SMSUtil.SUCCESS)) {
            return jsonView(FAIL_CODE, (String) verifyCode.get(SMSUtil.MSG));
        }
        //###初始化商户信息
        Organize superPlatOrganize = organizeService.getOrganizeById(loginUser.getOrganizeId());
        organize.setSuperiorPlatOrganizeName(superPlatOrganize.getOrganizeName());
        organize.setSuperiorPlatOrganizeId(superPlatOrganize.getId());
        //###初始化账户信息
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.web);
        if (account.getUserType() == UserType.shipperUser) {
            account.setTmsDriverDataState(Account.TmsDriverDataState.needless);
        } else {
            account.setTmsDriverDataState(Account.TmsDriverDataState.wait);
        }
        //###完成用户添加注册
        organize.setAddUserId(loginUser.getId());
        account.setAddUserId(loginUser.getId());
        organizeService.organizeRegister(organize, account);
        return jsonView(true, "客户注册成功！");
    }
    /**
     * 授权组织 个体注册 新
     * 验证码注册
     */
    @PostMapping("authorizedRegister")
    @SkipLoginVerify //开放注册/无需上游登录
    public ReturnData authorizedRegister(Organize organize, Account account) {
        if(getLoginUser().getUserType()!=UserType.adminUser&&getLoginUser().getUserType()!=UserType.platformUser){
            return jsonView(false, "您没有权限添加！");
        }
        ParamUtil.isNull(organize.getOrganType(),"授权主体未选择");
        ParamUtil.isNull(organize.getOrganizeName(),"请输入授权组织名称");
        ParamUtil.isNull(organize.getAuthorizedState(),"请选择授权状态");
        ParamUtil.isNull(organize.getTruckNumber(),"请输入授权数量");
        ParamUtil.isNull(account.getUsername(),"请输入授权账号");
        ParamUtil.isNull(account.getPhone(),"请输入手机号");
        ParamUtil.isNull(account.getVerCode(),"请输入验证码");
        ParamUtil.isNull(account.getPassword(),"请设置至少8位登录密码");
        if (account.getPassword().length() < 8) {
            return jsonView(false, "请设置至少8位登录密码！");
        }
        if (account.getPassword().length() > 18) {
            return jsonView(false, "密码大于16位，请将密码控制在（8-18位）！");
        }
        // ### 检查手机验证码
        Map<String, Object> verifyCode = SMSUtil.verifyCode(account.getPhone(), account.getVerCode(), SMSUtil.MsgType.organizeRegister);
        if (!(Boolean) verifyCode.get(SMSUtil.SUCCESS)) {
            return jsonView(FAIL_CODE, (String) verifyCode.get(SMSUtil.MSG));
        }
        organize.setUserType(UserType.truckerUser);
        organize.setAuthorized(true);
        account.setUserType(organize.getUserType());
        account.setOrganType(organize.getOrganType());
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.applets);
        organizeService.organizeRegister(organize, account);
        return jsonView(true, "注册成功");
    }

    /**
     * 手机号开放注册渠道  个体注册 新
     * 验证码注册
     */
    @PostMapping("phoneRegister")
    @SkipLoginVerify //开放注册/无需上游登录
    public ReturnData phoneRegister( Account account) {
        Organize organize=new Organize();
        organize.setUserType(UserType.truckerUser);
        organize.setOrganType(OrganType.individual);
        if (StringUtil.isEmpty(account.getPhone())) {
            return jsonView(false, "注册手机号不能为空！");
        }
        if (StringUtil.isEmpty(account.getSuperiorPlatId())) {
            return jsonView(false, "请绑定你的公司！");
        }
        if (StringUtil.isEmpty(account.getVerCode())) {
            return jsonView(false, "请输入收到的6位手机验证码！");
        }
        if (StringUtil.isEmpty(account.getPassword())) {
            return jsonView(false, "请设置至少8位登录密码！");
        }
        if (account.getPassword().length() < 8) {
            return jsonView(false, "请设置至少8位登录密码！");
        }
        if (account.getPassword().length() > 18) {
            return jsonView(false, "密码大于16位，请将密码控制在（8-18位）！");
        }
        // ### 检查手机验证码
        Map<String, Object> verifyCode = SMSUtil.verifyCode(account.getPhone(), account.getVerCode(), SMSUtil.MsgType.organizeRegister);
        if (!(Boolean) verifyCode.get(SMSUtil.SUCCESS)) {
            return jsonView(FAIL_CODE, (String) verifyCode.get(SMSUtil.MSG));
        }
        organize.setSuperiorPlatOrganizeId(account.getSuperiorPlatId());
        organize.setSuperiorPlatOrganizeName(account.getSuperiorPlatName());
        //###初始化账户信息
        account.setUsername(account.getPhone());
        account.setUserType(organize.getUserType());
        account.setOrganType(organize.getOrganType());
        account.setRoleType(RoleType.manager);
        account.setTerminalType(Account.TerminalType.applets);

        organizeService.organizeRegister(organize, account);
        return jsonView(true, "注册成功");
    }

    /**
     * 管理员添加
     * 员工注册通道
     */
    @PostMapping("employeeRegister")
    @Transactional
    public ReturnData employeeRegister(Account employee,String[] jurisdictionIds) {
        Account loginUser = getLoginUser();
        if (loginUser.getRoleType() != RoleType.manager) {
            return jsonView(false, "您无权添加员工");
        }
        if (StringUtil.isEmpty(employee.getRoleName())) {
            return jsonView(false, "请为员工角色名称账号！");
        }
        if ( StringUtil.isEmpty(employee.getPhone())) {
            return jsonView(false, "请填写员工手机号！");
        }
        if ( StringUtil.isEmpty(employee.getName())) {
            return jsonView(false, "请填写员工姓名！");
        }
        if ( StringUtil.isEmpty(employee.getPassword())) {
            return jsonView(false, "请设置员工密码！");
        }
        if ( StringUtil.isEmpty(employee.getVerCode())) {
            return jsonView(false, "请向员工索要验证码！");
        }
        Map<String, Object> verifyCode = SMSUtil.verifyCode(employee.getPhone(), employee.getVerCode(), SMSUtil.MsgType.employeeRegister);
        if (!(Boolean) verifyCode.get(SMSUtil.SUCCESS)) {
            return jsonView(FAIL_CODE, (String) verifyCode.get(SMSUtil.MSG));
        }
        employee.setRoleType(RoleType.employee);
        employee.setUsername(employee.getPhone());
        Organize organize = organizeService.getOrganizeById(loginUser.getOrganizeId());
        employee =accountService.employeeRegister(organize, employee,jurisdictionIds);

        return jsonView(true, "员工注册成功");
    }

    /**
     * 员工注册 更新
     * 生成密钥对
     */
    @PostMapping("generateKeyPair")
    public ReturnData generateKeyPair() {
        KeyPairMap keyPairMap = EncryptUtils.genKeyPairMap();
        String secretKey = EncryptUtils.aesEncrypt(keyPairMap.getPrivateKey(), null);
        String publicKey = EncryptUtils.aesEncrypt(keyPairMap.getPublicKey(), null);
        RedisClient.getInstance().hset(RedisKeys.ACCOUNT_API_PAIR_KEY, publicKey, secretKey);
        RedisClient.getInstance().expire(RedisKeys.ACCOUNT_API_PAIR_KEY, 60 * 60 * 24);//一天后过期
        return jsonView(true, "生成密钥对成功", publicKey);
    }

}
